package com.zhh.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.time.DateUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


public class JwtUtil {
    //创建jwt
    public static String createJwt(Map<String,Object> data, Integer minute) throws Exception{
        String selfKey = "dfafd1f6asfda56165adf9a1fsgafdgsdf5165sdfgsd5";
        Date curDate = new Date();
        SecretKey secretKey = Keys.hmacShaKeyFor(selfKey.getBytes(StandardCharsets.UTF_8));
        String jwt = Jwts.builder() //创建JwtBuilder对象，构建JWT
                .signWith(secretKey, SignatureAlgorithm.HS256) //使用指定的密钥和HS256签名算法对JWT进行签名
                .setExpiration(DateUtils.addMinutes(curDate,minute)) //设置JWT的过期时间
                .setIssuedAt(curDate) //设置JWT的签发时间
                .setId(UUID.randomUUID().toString().replaceAll("-","").toUpperCase()) //使用UUID生成一个唯一的标识符，并将其中的"-"替换为空字符串，并转换为大写
                .addClaims(data) //向JWT中添加自定义的声明
                .compact(); //将JWT生成为字符串形式
        return jwt;
    }

    //读取jwt
    public static Claims readJwt(String jwt) throws  Exception{
        String selfKey = "dfafd1f6asfda56165adf9a1fsgafdgsdf5165sdfgsd5";
        SecretKey secretKey = Keys.hmacShaKeyFor(selfKey.getBytes(StandardCharsets.UTF_8));
        Claims body = Jwts.parserBuilder().setSigningKey(secretKey)
                .build().parseClaimsJws(jwt).getBody();
        return body;
    }
}
